from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

from app.models.user import User

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")


def decode_token(token:str):
    # 实际项目中申请 JWT 解码
    if token == "admin-token":
        return {"id": 1, "is_admin": True}
    elif token == "user-token":
        return {"id":2, "is_admin": False}
    return None


async def verify_token(token: str = Depends(oauth2_scheme)) -> int:
    user = decode_token(token)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid token")
    return user["id"]


async def admin_required(user_id: int = Depends(verify_token)):
    user = await User.get(id=user_id)
    if not user.is_admin:
        raise HTTPException(status_code=403, detail="Admin only")
    return user

